package ufpr.ees.suhck.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import ufpr.ees.suhck.db.HibernateUtil;

public class GenericDaoImpl<T, PK extends Serializable>
        implements GenericDao<T, PK> {

    protected Class<T> entityClass;

    protected Session sf;

    public GenericDaoImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }

    @Override
    public T save(T t) {
        sf = HibernateUtil.getSessionFactory().openSession();
        sf.getTransaction().begin();
        sf.saveOrUpdate(t);

        sf.getTransaction().commit();
        return t;
    }

    @Override
    public T find(PK id) {
        sf = HibernateUtil.getSessionFactory().openSession();
        sf.getTransaction().begin();
        Object obj = sf.load(entityClass, id);
        sf.getTransaction().commit();
        return (T) obj;
    }

    @Override
    public T update(T t) {
        sf = HibernateUtil.getSessionFactory().openSession();
        sf.getTransaction().begin();
        sf.update(t);
        sf.getTransaction().commit();
        return t;
    }

    @Override
    public void delete(T t) {
        sf = HibernateUtil.getSessionFactory().openSession();
        sf.getTransaction().begin();
        sf.delete(t);
        sf.getTransaction().commit();
    }

    @Override
    public List<T> findAll() {
        sf = HibernateUtil.getSessionFactory().openSession();
        Query query = sf.createQuery("FROM " + entityClass.getName());
        List<T> objects = query.list();      
        sf.close();
        return objects;
    }

}
